package com.example.gulimall.ware.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.common.constant.WareConstant;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimall.ware.dao.PurchaseDetailDao;
import com.example.gulimall.ware.entity.PurchaseDetailEntity;
import com.example.gulimall.ware.service.PurchaseDetailService;


@Service("purchaseDetailService")
public class PurchaseDetailServiceImpl extends ServiceImpl<PurchaseDetailDao, PurchaseDetailEntity> implements PurchaseDetailService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        /*
        key: '华为',//检索关键字
        status: 0,//状态
        wareId: 1,//仓库id
        */
        String key = (String)params.get("key");
        String status = (String)params.get("status");
        String wareId = (String)params.get("wareId");

        final String _default = "0";

        IPage<PurchaseDetailEntity> page = this.page(
                new Query<PurchaseDetailEntity>().getPage(params),
                Wrappers.<PurchaseDetailEntity>lambdaQuery()
                .eq(StringUtils.isNotBlank(status)
                        && !_default.equalsIgnoreCase(status),
                        PurchaseDetailEntity::getStatus, status)
                .eq(StringUtils.isNotBlank(wareId)
                        && !_default.equalsIgnoreCase(wareId),
                        PurchaseDetailEntity::getWareId, wareId)
        );

        return new PageUtils(page);
    }

    @Override
    public void updateDetailByPurchaseIds(Set<Long> details) {

        if (CollectionUtil.isEmpty(details)) {
            return ;
        }

        List<PurchaseDetailEntity> detailEntities = this.baseMapper.selectList(
                Wrappers.<PurchaseDetailEntity>lambdaQuery()
                        .in(PurchaseDetailEntity::getPurchaseId, details)
        );

        List<PurchaseDetailEntity> entities = detailEntities.stream().map(
                a ->
                        new PurchaseDetailEntity()
                                .setStatus(WareConstant.PurchaseDetailsStatus.BUYING.getCode())
                                .setId(a.getId())
        ).collect(Collectors.toList());

        this.updateBatchById(entities);
    }

}